package freakin.wify;

import android.app.Application;
import android.util.Log;

public class WifiApp extends Application {
	
	private static final String TAG = "WifiApp";
	
	protected boolean serviceActive;
	
	protected DbHelper database;
	protected NetworkManager nm;
	
	protected long scanInterval;
	protected long sendInterval;
	
	protected Network nearestNetwork;
	
	protected String userName;
	protected String userPassword;
	protected int userId;
	
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "created application");
		
		scanInterval = 60 * 1000;		//scan every minute!
		sendInterval = 10 * 60 * 1000;
		
		userName = "";
		userPassword = "";
		userId = -1;
		
		database = new DbHelper(this);
		nm = new NetworkManager(getBaseContext(), database, this);
		
		nearestNetwork = null;
	}
	
	/**
	 * Deletes all networks saved on this device from the webservice.
	 * Used ONLY FOR DEBUGGING :)
	 * @return true, if deletion completed successfully, false if
	 * could not delete nets for any reason.
	 */
	public boolean deleteNetworksFromWebservice() {
		return nm.deleteNetworksFromWebservice();
	}
	
	/**
	 * Sets user name and password and logs in to the webservice.
	 * 
	 * @param user_name
	 * @param user_pass
	 */
	public void setUserPass(String user_name, String user_pass) {
		userName = user_name;
		userPassword = user_pass;
		
		if (!userName.equals("") && userName != null) {
			logIn();
		} else {
			Log.d(TAG, "unable to log in. UserName empty or null");
		}
	}
	
	private void logIn() {
		if (Utils.isConnected(getBaseContext())) {
			Log.d(TAG, "logging in...");
			SoapHelper sh = new SoapHelper();
			userId = sh.logIn(userName, userPassword);
			Log.d(TAG, "logged in to the webservice with userId: " + userId);
		} else
			Log.d(TAG, "unable to log in. No internet connection available");
	}
	
	/**
	 * If the WifiService is started, this method ought to be called,
	 * as it calls other, necessary methods on other objects, thus
	 * registering GPS updates listener, etc. 
	 */
	public void startService() {
		serviceActive = true;
		nm.start();
	}
	
	/**
	 * If the WifiService is stopped, this method ought to be called,
	 * as it calls other, necessary methods on other objects, thus
	 * unregistering GPS updates listener, frees some RAM. 
	 */
	public void stopService() {
		serviceActive = false;
		nm.stop();
	}

}
